/**
 * 添加项目
 */
function saveProjectSuperBtn(data) {
    let $projectForm = $('#projectAddForm');
    let $id = $projectForm.find('[name=id]');
    let $name = $projectForm.find('[name=name]');
    let $isShow = $projectForm.find('[name=isShow]');
    let $displayOrder = $projectForm.find('[name=displayOrder]');

    //弹框
    layer.open({
        title: '添加项目'
        , type: 1
        , area: ['55%', '70%']
        , content: $projectForm
        , btn: ["提交"]
        , yes: function () {
            // NProgress.start();
            let rootNode = tree.getTreeData('menu-tree')[0];
            //去掉 del 调整参数
            let eachNodes = function (data, isRem) {
                let nodeArr = [];
                for (let item of data) {

                    let del = (item.status == 'remove' || isRem);
                    //删除状态 && ID为null 直接过滤
                    if (del && (item.menuId == null || item.projectId != rootNode.id)) {
                        continue;
                    }

                    let menuTemp = {};
                    if (item.children && item.children.length > 0) {
                        menuTemp.childrenMenu = eachNodes(item.children, del);
                    }
                    //不是当前项目菜单新增
                    if (item.menuId != null && item.projectId == rootNode.id) {
                        menuTemp.id = item.menuId;
                    }
                    menuTemp.apiId = item.apiId;
                    menuTemp.applicationId = item.applicationId;
                    menuTemp.delete = del ?? false;
                    menuTemp.menuName = item.title;
                    nodeArr.push(menuTemp);
                }
                return nodeArr;
            }
            //保存项目
            saveSuperProject({
                id: $id.val()
                , name: $name.val()
                , isShow: $isShow[0].checked
                , displayOrder: $displayOrder.val()
                , menuList: eachNodes(rootNode.children)
            }, d => {
                layer.closeAll();
                dataTable.reload({});
            })
        }
    });
    //菜单树
    let menuTree = function (menus) {
        if (!menus) {
            return;
        }
        for (let menu of menus) {
            menu.menuId = menu.id;
            menu.id = 'menu-' + menu.id;
            menu.title = (menu.pcName || menu.menuName);
            menu.desc = (menu.type != null ? ' | ' + ApiType[menu.type] : '') + (menu.path ? ' | ' + menu.path : '');
            menu.children = menuTree(menu.childrenMenu);
            menu.childrenMenu = null;
        }
        return menus;
    }
    let menuTreeData;
    if (data == null) {
        $id.val('');
        $name.val('');
        $isShow[0].checked = true;
        $displayOrder.val('1');
        //菜单数据
        menuTreeData = [{
            title: '根' //一级菜单
            , disabled: true
            , children: [{
                title: 'web'
            }, {
                title: 'app'
            }]
        }];
    } else {
        $id.val(data.id);
        $name.val(data.name);
        $isShow[0].checked = data.isShow;
        $displayOrder.val(data.displayOrder);
        form.render("checkbox");
        getProjectSuperById(data.id, p => {
            menuTreeData = [{
                id: p.id
                , title: '根' //一级菜单
                , disabled: true
                , children: menuTree(p.branchList[0].menuList)
            }]
        })
    }
    //展示
    tree.render({
        id: 'menu-tree'  //绑定元素
        , elem: '#menu-tree'  //绑定元素
        , data: menuTreeData
        , showLine: false  //是否开启连接线
        , edit: ['add', 'update', 'del', 'transfer'] //操作节点的图标
    })
    //加载项目树
    selectProject(data => {
        //整理数据
        let projectTreeData = data.map(p => {
            p.title = p.name;
            p.desc = '项目';
            p.disabled = true;
            p.children = p.branchList.map(b => {
                b.title = b.name;
                b.desc = '分支';
                b.disabled = true;
                b.children = menuTree(b.menuList);
                return b;
            })
            p.branchList = null;
            p.projectConfigs = null;
            return p;
        });
        tree.render({
            id: 'project-tree'  //绑定元素
            , elem: '#project-tree'  //绑定元素
            , data: projectTreeData
            , showCheckbox: true  //是否显示复选框
            , showLine: false  //是否开启连接线
        });
    })
    $projectForm.removeClass("layui-hide");

}

/**
 * 保存项目
 */
function saveSuperProject(data, fun) {
    $.ajax({
        type: 'post',
        url: saveSuperProjectUrl,
        async: false,
        data: JSON.stringify(data),
        dataType: 'json',
        contentType: "application/json;charset=utf-8",
        error: ajaxError,
        success: function (data) {
            if (data.statusCode !== 200) {
                layer.msg(data.statusMsg);
                return;
            }
            fun(data.data);
        }
    })
}

/**
 * 查询所有项目信息
 */
function selectProject(fun) {
    $.ajax({
        type: 'get',
        url: listProjectTreeUrl,
        dataType: 'json',
        error: ajaxError,
        success: function (data) {
            if (data.statusCode !== 200) {
                layer.msg(data.statusMsg);
                return;
            }
            fun(data.data);
        }
    })
}

/**
 * 查询super项目信息
 */
function getProjectSuperById(id, fun) {
    $.ajax({
        type: 'get',
        url: getProjectSuperByIdUrl,
        async: false,
        data: {id: id},
        dataType: 'json',
        error: ajaxError,
        success: function (data) {
            if (data.statusCode !== 200) {
                layer.msg(data.statusMsg);
                return;
            }
            fun(data.data);
        }
    })
}

/**
 * 菜单树 筛选
 * @param that this
 * @param id treeId
 */
function treeSearch(that, id) {
    let content = $(that).val();
    //为null全部展示
    if (!content) {
        $('#' + id + '>.layui-tree .layui-tree-set').removeClass('layui-hide');
        return;
    }
    //只有一个时进行勾选
    let count = 0;
    let first = null;
    //过滤树
    let filterTree = function (menus) {
        let isShow = false;
        for (let menu of menus) {
            let childrenShow = false;
            let pack = $(menu).children('.layui-tree-pack');
            if (pack && pack.length > 0) {
                //递归遍历子项
                childrenShow = filterTree($(pack).children('.layui-tree-set'));
                if (childrenShow) {
                    $(pack).show();
                }
            }
            //先移除上次的
            $(menu).removeClass("layui-hide");
            let txt = $(menu).children('.layui-tree-entry').find('.layui-tree-txt').text();
            let mShow = inOf(txt, content);
            //满足记录次数 第一个菜单
            if (mShow) {
                count++;
                if (first == null) {
                    first = $(menu);
                }
            }
            //当前满足||子项满足 就展示
            mShow = mShow || childrenShow;
            if (!mShow) {
                $(menu).addClass("layui-hide");
            }
            //当前列表有一个true就返回给父true
            isShow = isShow || mShow;
        }
        return isShow;
    }
    //开始过滤
    filterTree($('#' + id + ">.layui-tree>.layui-tree-set"));
    console.log("满足条件数量：" + count);
    if (count === 1) {
        let input = first.find('input[same="layuiTreeCheck"]');
        input[0].checked = true;
        input.next().addClass("layui-form-checked")
    }
}